import 'dart:io';

import 'package:flutter/material.dart';
import '/util/logger_util.dart';
import 'package:webview_flutter/webview_flutter.dart';

import '/widget/app_bar.dart';

/// <summary>
/// todo: 网页浏览
/// author：zwb
/// dateTime： 2021/11/5 15:09
/// filePath： lib/page/show/show_web_page.dart
/// desc:
/// <summary>
///
class ShowWebPage extends StatefulWidget {
  final String? title;
  final String? url;
  final List<Widget>? actions;
  final double? width;
  final double? height;
  final int quarterTurns; // 0竖屏  1横屏
  const ShowWebPage({Key? key, this.title, this.url, this.actions, this.width, this.height, this.quarterTurns:0}) : super(key: key);

  @override
  _ShowWebPageState createState() => _ShowWebPageState();
}

class _ShowWebPageState extends State<ShowWebPage> {
  WebViewController? webViewController;
  int currentProgress = 0;
  String currentTitle = "";
  bool loading = false;
  String tag = 'webview_flutter';

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    // Enable hybrid composition.
    if (Platform.isAndroid) WebView.platform = SurfaceAndroidWebView();
  }

  @override
  Widget build(BuildContext context) {
    if(!loading) currentTitle = "加载中 $currentProgress%";
    return Scaffold(
      appBar: appBarWidget(
        title: widget.title ?? currentTitle,
        actions: widget.actions,
      ),
      body: Column(
        children: [
          Expanded(child:RotatedBox(quarterTurns: widget.quarterTurns, child: WebView(
            initialUrl: widget.url,
            javascriptMode: JavascriptMode.unrestricted,
            onWebViewCreated: (c) => webViewController = c,
            gestureNavigationEnabled: true,
            onProgress: (int progress) {
              setState(() => currentProgress = progress);
              logger("WebView 正在加载 (进度 : $progress%)",tag: tag);
            },
            javascriptChannels: <JavascriptChannel>{
              _javascriptChannel(context),
            },
            navigationDelegate: (NavigationRequest request) {
              return navigationDelegate(request);
            },
            onPageStarted: (String url) {
              setState(() => loading  = false);
              logger('页面 启动加载 进度: $url',tag: tag);
            },
            onPageFinished: (String url) {
              onPageFinished(url);
            },
          ),) // 横屏显示
          )
        ],
      ),
    );
  }

  /// todo：js交互操作
  JavascriptChannel _javascriptChannel(BuildContext context) {
    return JavascriptChannel(
        name: 'Toaster',
        onMessageReceived: (JavascriptMessage message) {
          logger(message,tag: tag);
          setState(()=> currentTitle = message.message);
        });
  }

  /// todo：网址导航操作
  NavigationDecision navigationDelegate(NavigationRequest request){
    // 对一些网站进行阻止
    if (request.url.startsWith('https://www.youtube.com/')) {
      logger('被阻止执行的导航 to $request}',tag: tag);
      return NavigationDecision.prevent;
    }
    logger('允许执行的导航 to $request',tag: tag);
    return NavigationDecision.navigate;
  }

  /// todo：完成加载
  void onPageFinished(String url) {
    logger('页面 完成加载 进度: $url',tag: tag);
    setState(() => loading  = true);
    webViewController!.evaluateJavascript("document.title").then((result){
      setState(() => currentTitle = result);
    });
  }
}
